/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */

package com.tengtong.duang.web.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tengtong.duang.action.DispatchManager;
import com.tengtong.duang.web.commons.ClientRequestMethod;
import com.tengtong.duang.web.servlet.impl.WebRequestContextImpl;

/**
 * 使用 Servlet 3.x 的注解来定义一个 servlet
 * 
 * @author mling
 *
 */
@WebServlet(name="ActionServlet", urlPatterns={"/"}, loadOnStartup=1)
public class ServletDispatcher extends HttpServlet{
	
	private DispatchManager dispatcher;

	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		dispatcher = new SimpleDispatchManager(config);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doDispatch(ClientRequestMethod.Get, req, resp);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doDispatch(ClientRequestMethod.Post, req, resp);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doDispatch(ClientRequestMethod.Put, req, resp);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doDelete(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doDispatch(ClientRequestMethod.Delete, req, resp);
	}

	/**
	 * 请求分派
	 * 
	 * @param requestMethod
	 * @param req
	 * @param resp
	 */
	private void doDispatch(ClientRequestMethod requestMethod, HttpServletRequest req, HttpServletResponse resp) {
		dispatcher.dispatch(new WebRequestContextImpl(requestMethod, req, resp));
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

}
